(function() {
	var $table = $("table.inventory-items");
	var $wrapper = $table.parent();
	
	function selectionChanged($row)
	{
//		var selectedItems = $wrapper.data('items');
//		if (!selectedItems)
//		{
//			selectedItems = [];
//		}
//		var num_iid = $row.attr("num_iid");
//		var selected = $("input", $row).attr("checked");
//		if (selected)
//		{
//			var found = $.grep(selectedItems, function(a){
//				return a == num_iid;
//			}, false);
//			if (found.length == 0)
//			{
//				selectedItems.push(num_iid);
//			}
//		}
//		else
//		{
//			selectedItems = $.grep(selectedItems, function(a){
//				return a == num_iid;
//			}, true);
//		}
//		$wrapper.data('items', selectedItems);
	}
	
	$table.mytable({selectionChanged: selectionChanged});
	
	$('.editor input[name="time"]', $table).timepicker({});

	$('a.list-link, a.change-job', $table).click(function(){
		var $tr = $(this).closest("tr");
		var virtual = $tr.attr('virtual');
		if ('true' == virtual)
		{
			alert('对不起，无法上架虚拟物品。');
			return false;
		}
		$('.editor', $tr).show();
		var dayOfWeek = $('td.list-time', $tr).attr('day-of-week');
		$('option', $tr).removeAttr('selected');
		$('option[value="' + dayOfWeek + '"]', $tr).attr('selected', 'selected');
		return false;
	});
	
	$('button.ok', $table).click(function(){
		var $editor = $(this).closest('.editor');
		var dayOfWeek = $('select', $editor).val();
		var time = $('input', $editor).val();
		var numIid = $(this).closest("tr").attr("num_iid");
		$.ajax({
			url: 'schedule-listing',
			data: {numIids: numIid, dayOfWeek: dayOfWeek, time: time},
			type: 'POST',
			success: function(data, textStatus, jqXHR) {
				if (window.common.isOverflow(jqXHR))
				{
					return false;
				}
				window.listInventory.reload();
			},
			error: function(jqXHR, textStatus, errorThrown) {
				alert(textStatus);
				var headers = jqXHR.getAllResponseHeaders();
				alert(headers);
				alert(errorThrown);
			}
		});
		return false;
	});
	
	$('button.cancel', $table).click(function(){
		var $editor = $(this).closest('.editor');
		$editor.hide();
		return false;
	});
	
	$('a.cancel-job').click(function(){
		var $tr = $(this).closest("tr");
		var numIid = $tr.attr("num_iid");
		$.ajax({
			url: 'cancel-job',
			data: {numIids: numIid},
			type: 'POST',
			success: function(data) {
				window.listInventory.reload();
			},
			error: function(jqXHR, textStatus, errorThrown) {
				alert(textStatus);
				var headers = jqXHR.getAllResponseHeaders();
				alert(headers);
				alert(errorThrown);
			}
		});
		return false;
	});
})();